package com.itboye.jinpuyiyuan.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.widget.Toast;

import com.alibaba.mobileim.channel.event.IWxCallback;
import com.alibaba.mobileim.channel.util.YWLog;
import com.alibaba.mobileim.utility.IMNotificationUtils;
import com.google.gson.Gson;
import com.itboye.jinpuyiyuan.MainActivity;
import com.itboye.jinpuyiyuan.R;
import com.itboye.jinpuyiyuan.activity.login.BindPhoneActivity;
import com.itboye.jinpuyiyuan.activity.login.LoginActivity;
import com.itboye.jinpuyiyuan.bean.PersonBean;
import com.itboye.jinpuyiyuan.bean.WXBean;
import com.itboye.jinpuyiyuan.presenter.BranchAddressPresenter;
import com.itboye.jinpuyiyuan.utils.IMKit.LoginSampleHelper;
import com.itboye.jinpuyiyuan.utils.IMKit.NotificationInitSampleHelper;
import com.itboye.jinpuyiyuan.utils.IMKit.UserProfileSampleHelper;
import com.itboye.jinpuyiyuan.utils.OkHttpUtils;
import com.itboye.jinpuyiyuan.utils.sputil.Const;
import com.itboye.jinpuyiyuan.utils.sputil.SPUtils;
import com.itboye.jinpuyiyuan.utils.volley.CodeErrorException;
import com.itboye.jinpuyiyuan.utils.volley.ResultEntity;
import com.itboye.jinpuyiyuan.widget.FilterUtil;
import com.itboye.jinpuyiyuan.widget.loadingutil.MAlert;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;

import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.mm.sdk.openapi.BaseReq;
import com.tencent.mm.sdk.openapi.BaseResp;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Observable;
import java.util.Observer;

import static com.itboye.jinpuyiyuan.activity.home.finddoctor.DoctorDetailActivity.TAG;


/**
 * Created by Administrator on 2018/1/19 0019.
 */

public class WXEntryActivity extends Activity implements IWXAPIEventHandler, Observer {
    private IWXAPI api;
    private BranchAddressPresenter presenter;
    public  LoginSampleHelper loginSampleHelper;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_illessinfo);
         regToWx();
        //init SDK 添加消息接受监听
        loginSampleHelper = LoginSampleHelper.getInstance();
         presenter=new BranchAddressPresenter(this);
        boolean b = api.handleIntent(getIntent(), this);
//        MAlert.alert(b+"");

    }


    @Override
    public void onReq(com.tencent.mm.opensdk.modelbase.BaseReq baseReq) {

//        MAlert.alert("fasongchuqule");
    }

    @Override
    public void onResp(com.tencent.mm.opensdk.modelbase.BaseResp baseResp) {

        Log.d("code===","onPayFinish,errCode="+ baseResp.toString());

        if(baseResp.getType()== ConstantsAPI.COMMAND_PAY_BY_WX){
            Log.d("code===","onPayFinish,errCode="+ baseResp.errCode);
//            AlertDialog.Builder builder = new AlertDialog.Builder(this);
//            new AlertDialog.Builder(this);
//            builder.setTitle(R.string.app_tip);
        }else {
            String code = ((SendAuth.Resp) baseResp).code;
            presenter.loginByWX("","xxxxxx",code);
            Log.d("code===",code);
        }
//        //登录回调
//        switch (baseResp.errCode) {
//            case BaseResp.ErrCode.ERR_OK:
//                String code = ((SendAuth.Resp) baseResp).code;
//                //获取用户信息
//                getAccessToken(code);
//                break;
//            case BaseResp.ErrCode.ERR_AUTH_DENIED://用户拒绝授权
//                finish();
//                break;
//            case BaseResp.ErrCode.ERR_USER_CANCEL://用户取消
//                finish();
//                break;
//            default:
//                finish();
//                break;
//        }

//        api.handleIntent(getIntent(),this);
//        MAlert.alert("huilaile");
    }

    private void getAccessToken(String code) {
        //获取授权
        StringBuffer loginUrl = new StringBuffer();
        loginUrl.append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=")
                .append(Const.APP_ID_WX)
                .append("&secret=")
                .append(Const.APP_SECRET)
                .append("&code=")
                .append(code)
                .append("&grant_type=authorization_code");

        OkHttpUtils.ResultCallback<String> resultCallback = new OkHttpUtils.ResultCallback<String>() {
            @Override
            public void onSuccess(String response) {
                String access = null;
                String openId = null;
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    access = jsonObject.getString("access_token");
                    openId = jsonObject.getString("openid");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                //获取个人信息
                String getUserInfo = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access + "&openid=" + openId;
                OkHttpUtils.ResultCallback<String> reCallback = new OkHttpUtils.ResultCallback<String>() {
                    @Override
                    public void onSuccess(String responses) {

                        String nickName = null;
                        String sex = null;
                        String city = null;
                        String province = null;
                        String country = null;
                        String headimgurl = null;
                        String openid=null;
                        String unionid=null;
                        try {
                            JSONObject jsonObject = new JSONObject(responses);

                            openid = jsonObject.getString("openid");
                            nickName = jsonObject.getString("nickname");
                            sex = jsonObject.getString("sex");
                            city = jsonObject.getString("city");
                            province = jsonObject.getString("province");
                            country = jsonObject.getString("country");
                            headimgurl = jsonObject.getString("headimgurl");
                            unionid = jsonObject.getString("unionid");

                            //微信登录
                            Intent intent = new Intent(WXEntryActivity.this, LoginActivity.class);
                            intent.putExtra("wxapp_openid",openid);
                            intent.putExtra("wx_unionid",unionid);
                            intent.putExtra("wx_nickname",nickName);
                            intent.putExtra("wx_head",headimgurl);
                            startActivity(intent);
                            WXEntryActivity.this.finish();

//                            presenter.login(nickName,headimgurl,openid,unionid,"");
//                            loadNetData(1, openid, nickName, sex, province,
//                                    city, country, headimgurl, unionid);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onFailure(Exception e) {
                        Toast.makeText(WXEntryActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
                        finish();
                    }
                };
                OkHttpUtils.get(getUserInfo, reCallback);
            }

            @Override
            public void onFailure(Exception e) {
                Toast.makeText(WXEntryActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
                finish();
            }
        };
        OkHttpUtils.get(loginUrl.toString(), resultCallback);
    }



    //微信介入
    private  void  regToWx(){
        api= WXAPIFactory.createWXAPI(this,Const.APP_ID_WX,true);
        api.registerApp(Const.APP_ID_WX);
    }

    @Override
    public void update(Observable o, Object arg) {
        ResultEntity resultEntity= (ResultEntity) arg;
        if (resultEntity!=null){

            if (Integer.parseInt(resultEntity.getCode())==-2){//未绑定手机号 去绑定手机
                MAlert.alert("微信未绑定手机号需要绑定手机号");
                CodeErrorException ecp= (CodeErrorException) resultEntity.getData();
                Log.d("=======",ecp.getLocalizedMessage());
                PersonBean wxBean= new Gson().fromJson(ecp.getLocalizedMessage(),PersonBean.class);
                Intent intent = new Intent(WXEntryActivity.this, BindPhoneActivity.class);
                intent.putExtra("wxapp_openid",wxBean.getWxapp_openid());
                intent.putExtra("wx_unionid",wxBean.getWx_unionid());
                intent.putExtra("wx_nickname",wxBean.getNickname());
                intent.putExtra("wx_head",wxBean.getHead());
                startActivity(intent);
                WXEntryActivity.this.finish();
            }else if(Integer.parseInt(resultEntity.getCode())==0) { //登录成功

                PersonBean personBean= (PersonBean) resultEntity.getData();
                Log.d("login==",personBean.getAlibaichuan_id()+"=="+personBean.getPassword()
                        +"uid="+personBean.getUid());
                Intent intent = new Intent();
                intent.putExtra("person",personBean);
                intent.setAction("loginByWX");
                sendBroadcast(intent);
                Log.d("role",personBean.getRoles().get(0)+"");
                WXEntryActivity.this.finish();

            }else {
                MAlert.alert("获取微信登录信息失败");
                WXEntryActivity.this.finish();
            }
        }
    }


    private static void init(String userId, String appKey){
        //初始化imkit
        LoginSampleHelper.getInstance().initIMKit(userId, appKey);
        //自定义头像和昵称回调初始化(如果不需要自定义头像和昵称，则可以省去)
        UserProfileSampleHelper.initProfileCallback();
        //通知栏相关的初始化
        NotificationInitSampleHelper.init();

    }
}
